require "wondercap/lib/utils/dependency_resolver"
require "wondercap/lib/utils/logging"

module ::Wondercap
module Deployment
module NameFilters
 
  class AppendRuntimeDependentFilter
    def call(names, base_conf)
      prev_snap ||= base_conf.area.current_snapshot
      return names unless prev_snap

      getter = lambda do |name|
        dep = prev_snap.find_deployment_by_name(name)
        dep.runtime_dependencies
      end
      
      deps_resolver = DependencyResolver.new(getter)
      deps_resolver.add_dependent(names, prev_snap.deployments.map { |dep| dep.name })
    end
  end

  module RequiredRuntimeDependenciesResolver
    include Logging

    def deps_resolver(base_conf)
      getter = lambda do |name|
        logger.debug "getting required deps for #{name}"
        conf = base_conf.mc.get_configuration(name)
        return nil unless conf

        conf.runtime_dependencies
      end

      DependencyResolver.new(getter)
    end
  end

  class AppendRequiredRuntimeDependencies
    include RequiredRuntimeDependenciesResolver

    def call(names, base_conf)
      deps_resolver(base_conf).add_required(names).to_a
    end
  end

  class OrderByRuntimeDependenciesFilter
    include RequiredRuntimeDependenciesResolver

    def call(names, base_conf)
      deps_resolver(base_conf).order_by_dependencies(names).to_a
    end
  end

end
end
end

define_name_filter :append_runtime_dependent, Wondercap::Deployment::NameFilters::AppendRuntimeDependentFilter.new
define_name_filter :append_runtime_required, Wondercap::Deployment::NameFilters::AppendRequiredRuntimeDependencies.new
define_name_filter :order_by_runtime_dependencies, Wondercap::Deployment::NameFilters::OrderByRuntimeDependenciesFilter.new
